package com.qf.dao.impl;

import com.qf.dao.GoodsDao;
import com.qf.domain.Goods;
import com.qf.utils.DataSourceUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;

public class GoodsDaoImpl implements GoodsDao {
    private QueryRunner queryRunner = new QueryRunner(DataSourceUtil.getDataSource());
    @Override
    public long getCount(String where, List<Object> params) {
        String sql = " select count(*) from tb_goods "+where;
        try {
            return queryRunner.query(sql,new ScalarHandler<>(),params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public List<Goods> selectByPage(int page_num, int page_size, String where, List<Object> params) {
        params.add((page_num-1)*page_size);
        params.add(page_size);
        String sql = " select * from tb_goods "+where+" order by id limit ?,? ";
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Goods.class),params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public Goods selectById(Integer gid) {

        String sql = " select * from tb_goods where id=? ";
        try {
            return queryRunner.query(sql,new BeanHandler<>(Goods.class),gid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(Goods goods) {
        String sql = " insert into tb_goods (name,pubdate,picture,price,star,intro,typeid) values (?,?,?,?,?,?,?) ";

        Object[] params = {goods.getName(),goods.getPubdate(),goods.getPicture(),goods.getPrice(),goods.getStar(),goods.getIntro(),goods.getTypeid()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }


    //后加:后台查询商品
    @Override
    public List<Goods> adminSelect(StringBuilder where, List<Object> params) {

        String sql = "select * from tb_goods "+where;
        try {
            return queryRunner.query(sql,new BeanListHandler<>(Goods.class),params.toArray());
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    //后台删除商品
    @Override
    public void delete(int gid) {
        String sql = "delete from tb_goods where id=? " ;
        try {
             queryRunner.update(sql,gid);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
